package com.kexilo.core.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kexilo.core.common.core.web.domain.R;
import com.kexilo.core.common.utils.ServletUtils;
import com.kexilo.core.common.utils.StringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;

/**
 * 自定义访问拒绝处理器，返回JSON
 * 
 * @author Kexilo
 */
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler, Serializable {
    
    private static final Logger log = LoggerFactory.getLogger(AccessDeniedHandlerImpl.class);
    
    private static final long serialVersionUID = -6584158895557938073L;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e)
            throws IOException {
        int code = HttpStatus.FORBIDDEN.value();
        String msg = StringUtils.format("请求访问：{}，权限不足，请联系管理员", request.getRequestURI());
        
        log.warn("权限不足: {}", msg);
        ServletUtils.renderString(response, new ObjectMapper().writeValueAsString(R.fail(code, msg)));
    }
}
